{% extends "base.html" %}

{% block content %}
<div class="game-list-container">
    <div class="game-list">
        <ul class="game-items">
            {% for game in games %}
            <li class="game-item {% if game.category == 'official' %}official{% else %}temp{% endif %}" data-game-id="{{ game.game_id }}">
                <div class="game-date">{{ game.created_at.strftime('%Y-%m-%d') }}</div>
                <div class="game-title">{{ game.title }}</div>
            </li>
            {% endfor %}
        </ul>
    </div>
    <div class="game-details">
        <div id="game-info">
            <p>请选择一个游戏查看详情</p>
        </div>
        <div id="word-list">
            <!-- 单词列表将通过 JavaScript 动态加载 -->
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const gameItems = document.querySelectorAll('.game-item');
    const gameInfo = document.getElementById('game-info');
    const wordList = document.getElementById('word-list');

    function selectGame(gameItem) {
        // Remove 'selected' class from all game items
        gameItems.forEach(item => item.classList.remove('selected'));
        // Add 'selected' class to the clicked game item
        gameItem.classList.add('selected');

        const gameId = gameItem.getAttribute('data-game-id');
        fetch(`/game_details/${gameId}`)
            .then(response => response.json())
            .then(data => {
                gameInfo.innerHTML = `
                    <h3>${data.title}</h3>
                    <p>${data.description}</p>
                    <p>${data.created_at}</p>
                    <p><a href="/game_spell?game_id=${gameId}" target="_blank">Spell it >></a></p>
                    <p><a href="/game_translate?game_id=${gameId}" target="_blank">Translate >></a></p>
                `;
                wordList.innerHTML = '<ul>';
                data.words.forEach(word => {
                    wordList.innerHTML += `
                        <li class="word-item">
                            <span class="word-english">${word.english}</span>
                            <span class="word-chinese">${word.chinese}</span>
                        </li>
                    `;
                });
                wordList.innerHTML += '</ul>';
            });
    }

    gameItems.forEach(item => {
        item.addEventListener('click', function() {
            selectGame(this);
        });
    });

    // Select the first game by default
    if (gameItems.length > 0) {
        selectGame(gameItems[0]);
    }
});
</script>

{% endblock %}
